package com.application.chiettinhdienluc.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.SharedPreferencesData;
import com.application.chiettinhdienluc.db.DonViQuanLyDataSource;
import com.application.chiettinhdienluc.db.MySQLiteHelper;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.DonViQuanLyModel;
import com.application.chiettinhdienluc.utils.DeviceState;
import com.application.chiettinhdienluc.utils.Utils;


public class SettingsActivity extends SherlockFragmentActivity {

	final Context context = this;
	private Resources res;
	public static final String BOOL_EXTRA_START_FROM_LOGIN = "extra_start_from_login";

	EditText edt_local_ip;
	EditText edt_internet_ip;
	EditText edt_service_port;
	EditText edt_ma_donviquanly;
	
	TextView tv_ma_thietbi_value;
	
	TextView tv_import_database;
	TextView tv_file_name;
	TextView tv_file_date;
	
	ImageButton export_button;
	ImageButton import_button;
	
	boolean bStartFromLogin = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.settings_view);
		
		res = getResources();
		getSupportActionBar().setTitle(res.getString(R.string.str_title_viewlist_settings));

		edt_local_ip = (EditText) findViewById(R.id.edt_local_ip);
		edt_internet_ip = (EditText) findViewById(R.id.edt_internet_ip);
		edt_service_port = (EditText) findViewById(R.id.edt_service_port);
		
		edt_ma_donviquanly  = (EditText) findViewById(R.id.edt_ma_donviquanly);
		tv_ma_thietbi_value = (TextView) findViewById(R.id.tv_ma_thietbi_value);
		tv_ma_thietbi_value.setText(DeviceState.getDeviceId());	
		
		
		LoadSettings();

		
		ActionBar actionbar = getSupportActionBar();
		if(actionbar != null)
		{
			actionbar.setDisplayHomeAsUpEnabled(true);
			actionbar.setDisplayShowHomeEnabled(true);
		}
		
		Bundle bundle = getIntent() != null ? getIntent().getExtras() : null;
		
		if(bundle != null)
		{
			bStartFromLogin = bundle.containsKey(BOOL_EXTRA_START_FROM_LOGIN) ? bundle.getBoolean(BOOL_EXTRA_START_FROM_LOGIN) : false;
		}
		
		if (bStartFromLogin){
			showDialogWarningInputKHInfo();
		}
		
		
		String file_date = MySQLiteHelper.getInstance().getBackupDbFileDate();
		
		
		export_button = (ImageButton) findViewById(R.id.export_button);
		export_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MySQLiteHelper.getInstance().exportDataBase();
				String file_date = MySQLiteHelper.getInstance().getBackupDbFileDate();
				
				if(!TextUtils.isEmpty(file_date)) {
					
					tv_import_database.setVisibility(View.VISIBLE);
					import_button.setVisibility(View.VISIBLE);
				
					
					tv_file_name.setVisibility(View.VISIBLE);			
					tv_file_date.setText(res.getString(R.string.ngay_sao_luu) + " " + file_date);
					tv_file_date.setVisibility(View.VISIBLE);
				}
				else
				{
					tv_import_database.setVisibility(View.INVISIBLE);
					import_button.setVisibility(View.INVISIBLE);
				
					tv_file_name.setVisibility(View.INVISIBLE);
					tv_file_date.setVisibility(View.INVISIBLE);
				}
				
				
			}
		});
		
		
		import_button = (ImageButton) findViewById(R.id.import_button);		
		import_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MySQLiteHelper.getInstance().importDataBase();
				
			}
		});
		
		
		
		tv_import_database = (TextView) findViewById(R.id.tv_import_database);	
		tv_file_name = (TextView) findViewById(R.id.tv_file_name);			
		tv_file_date = (TextView) findViewById(R.id.tv_file_date);	
		
		if(!TextUtils.isEmpty(file_date)) {
			
			tv_import_database.setVisibility(View.VISIBLE);
			import_button.setVisibility(View.VISIBLE);
		
			tv_file_name.setVisibility(View.VISIBLE);			
			tv_file_date.setText(res.getString( R.string.ngay_sao_luu) + " " + file_date);
			tv_file_date.setVisibility(View.VISIBLE);
		}
		else
		{
			tv_import_database.setVisibility(View.INVISIBLE);
			import_button.setVisibility(View.INVISIBLE);
			
			tv_file_name.setVisibility(View.INVISIBLE);
			tv_file_date.setVisibility(View.INVISIBLE);
		}
		
	}
	
	private void showDialogWarningInputKHInfo() {
		Dialog dialog = null;
		ConfirmDialog.ConfirmBuilder customBuilder = new ConfirmDialog.ConfirmBuilder(this);
		String msg = res.getString(R.string.str_warning_missing_pb_id_at_first_start);

		customBuilder.setTitle(res.getString(R.string.str_thongBao))
		.setMessage(msg)
		.setPositiveButton(res.getString(R.string.str_btn_ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null) dialog.dismiss();				
			}
		});
		dialog = customBuilder.create();
		
		if(dialog != null) dialog.show();
	}
	

	private void SaveSettings() {
		SharedPreferencesData.setMaDonViQuanLy(MainApplication.getAppContext(), edt_ma_donviquanly.getText().toString().trim());
		
		SharedPreferencesData.setLocalServerIp(MainApplication.getAppContext(), edt_local_ip.getText().toString().trim());
		SharedPreferencesData.setInternetServerIp(MainApplication.getAppContext(), edt_internet_ip.getText().toString().trim());
		SharedPreferencesData.setServicePort(MainApplication.getAppContext(), edt_service_port.getText().toString().trim());
		
		DonViQuanLyDataSource dvDataSource = new DonViQuanLyDataSource(MainApplication.getAppContext());		
		DonViQuanLyModel donvi = dvDataSource.getDonViByMaDonVi(SharedPreferencesData.getMaDonViQuanLy(MainApplication.getAppContext()));		
		if(donvi!=null) {		    
		    MainApplication.setMaKhuVuc(donvi.getKhuVuc());
		    Log.i("Ma Don Vi",  edt_ma_donviquanly.getText().toString().trim());
		    Log.i("Ma Khu Vuc", MainApplication.getMaKhuVuc());
		}		
	}

	private void LoadSettings() {
		
		String localIp = SharedPreferencesData.getLocalServerIp(MainApplication.getAppContext());
		String internetIp = SharedPreferencesData.getInternetServerIp(MainApplication.getAppContext());
		String port = SharedPreferencesData.getServicePort(MainApplication.getAppContext());
		String maDonViQuanLy = SharedPreferencesData.getMaDonViQuanLy(MainApplication.getAppContext());
	
		
		edt_local_ip.setText(localIp);	
		edt_internet_ip.setText(internetIp);	
		edt_service_port.setText(port);	
		edt_ma_donviquanly.setText(maDonViQuanLy);
		
	}	
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
            case android.R.id.home:
            	if(bStartFromLogin)
            	{
            		Intent localIntent = new Intent(SettingsActivity.this, com.application.chiettinhdienluc.ui.DanhMucHsoActivity.class);
					localIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(localIntent);
            	}
            	finish();
                break;
                
            case ID_ACTION_SAVE:
            	SaveSettings() ;
            	Utils.showMess(res.getString(R.string.str_save_setting_success));
            	
    			break;
        }

        return super.onOptionsItemSelected(item);
    }
	
	@Override
	public void onBackPressed() {
    	if(bStartFromLogin)
    	{
    		Intent localIntent = new Intent(SettingsActivity.this, com.application.chiettinhdienluc.ui.DanhMucHsoActivity.class);
			localIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(localIntent);
    	}
    	finish();
	}
	
	private final int ID_ACTION_SAVE = 1;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, ID_ACTION_SAVE, Menu.NONE, "Save").setIcon(R.drawable.content_save).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}

}
